﻿using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using Yz.Base;
using Yz.Core.Apis;
using Yz.Mvc.Authentication;

namespace Yz.ApiService.Filters
{
    public class JwtAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var authorization = actionContext.Request.Headers.Authorization;
            if (authorization == null || authorization.Scheme != "Bearer" || string.IsNullOrEmpty(authorization.Parameter))
            {
                HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
                actionContext.Response = actionContext.Request.CreateResponse(
                    ApiDataFactory.CreateApiData(new ApiModel(), ApiDataCode.tokenFail, ApiDataMsg.tokenFail));
                return;
            }
            var token = authorization.Parameter;
            var principal = JwtManager.GetPrincipal(token);
            if (principal == null || principal.Identity == null || !principal.Identity.IsAuthenticated)
            {
                HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
                actionContext.Response = actionContext.Request.CreateResponse(
                    ApiDataFactory.CreateApiData(new ApiModel(), ApiDataCode.tokenFail, ApiDataMsg.tokenFail));
            }
            HttpContext.Current.User = principal;
            HttpContext.Current.Response.AddHeader("AuthenticationStatus", "Authorized");
        }

    }
}